package LeetCode.LC29;

/**
 * @author corn
 * @create 2020-11-08-15:43
 */
public class Solution1 {
    public int divide(int dividend, int divisor) {
        if(dividend == 0){
            return 0;
        }
        if(divisor == 1){
            return dividend;
        }
        if(divisor == -1){
            return dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : -dividend;
        }
        //确定结果正负
        boolean flag = true;
        if((dividend > 0 && divisor < 0) ||(dividend < 0 && divisor > 0)){
            flag = false;
        }

        dividend = dividend < 0 ? dividend : -dividend;
        divisor = divisor < 0 ? divisor : -divisor;

        //简单概括为： 60/8 = (60-32[8<<2])/8 + 4 = (60-32[8<<2]-16[8<<1])/8 + 2 + 4 = 1 + 2 + 4 = 7

        int sol = cal(dividend, divisor);
        return flag ? sol : -sol;
    }
    public int cal(int dividend, int divisor){
        if(dividend > divisor){
            return 0;
        }
        int count = 1;
        int temp = divisor;
        while(temp > Integer.MIN_VALUE /2 && (temp<<1) > dividend){
            count = count<<1;
            temp = temp<<1;
        }
        return count + cal(dividend - temp, divisor);
    }
}
